package cn.wang.cart.service;

import cn.wang.auth.pojo.UserInfo;
import cn.wang.cart.interceptor.CartInterceptor;
import cn.wang.cart.pojo.Cart;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String REDIS_CART_PREFIX = "user:carts:";

    public void addOrUpdateCart(Cart cart) {
        // 获取请求用户
        UserInfo user = CartInterceptor.getUserInfo();
        // 用hash来存储用户购物车的信息, 其中hkey为商品的sukid, 值是cart对象
        BoundHashOperations<String, String, Cart> ops = redisTemplate.boundHashOps(REDIS_CART_PREFIX + user.getId());
        // 1. 从redis中获取值, 判断是否存在
        String skuId = cart.getSkuId().toString();
        if (ops.hasKey(skuId)) {
            // 存在进行更新
            Cart redisCart = ops.get(skuId);
            // 对其中的数量进行更新
            redisCart.setNum(redisCart.getNum() + cart.getNum());
            redisCart.setPrice(redisCart.getPrice() + cart.getPrice());
            // 更新redis中的数据
            ops.put(skuId, redisCart);
        } else {
            // 不存在新增
            ops.put(skuId, cart);
        }
    }

    public List<Cart> queryCarts() {
        UserInfo userInfo = CartInterceptor.getUserInfo();
        if (userInfo == null){
            return null;
        }
        // 判断是否穿在userInfo的记录
        if (!redisTemplate.hasKey(REDIS_CART_PREFIX+userInfo.getId())) {
            return null;
        }
        BoundHashOperations<String,String,Cart> ops = redisTemplate.boundHashOps(REDIS_CART_PREFIX + userInfo.getId());
        List<Cart> carts = ops.values();
        return carts;
    }
}
